package com.syt.cellphone.information.ui.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView


/**
 *  @author: syt
 *  创建时间: 2020/7/22 10:25
 *  @describe   倒计时文本控件
 */
class CountdownTextView @JvmOverloads constructor (
        context: Context,
        attrs: AttributeSet ?= null,
        defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr), Runnable {

    /**
     * 倒计时默认3s
     */
    var countDownNumber = 3

    /**
     * 倒计时默认提示语：跳过
     */
    var countDownHint = "跳过"

    /**
     * 当前的时间
     */
    private var mCurrentSecond: Int = countDownNumber

    /**
     * 记录原本的文本
     */
    private var mRecordText : CharSequence = text

    /**
     * 定义接口回调
     */
    private lateinit var mCallBackWork: CallBackWork

    @SuppressLint("SetTextI18n")
    override fun run() {
        if (mCurrentSecond <= 0) {
            stop()
            text = countDownHint
        } else {
            text = "$mCurrentSecond $countDownHint"
            postDelayed(this, 1000)
            mCallBackWork.getCurrentSecond(mCurrentSecond)
            mCurrentSecond --

        }
    }

    fun start() {
        // 倒计时开始，当前时间等于默认时间
        mCurrentSecond = countDownNumber
        // 执行信息队列
        post(this)
    }

    fun stop() {
        text = mRecordText
        mCallBackWork.stopWork()
    }

    override fun onDetachedFromWindow() {
        // 移除延迟任务，避免内存泄漏
        removeCallbacks(this)
        super.onDetachedFromWindow()
    }

    /**
     * 设置回调监听
     */
    fun initCallBack(callBackWork: CallBackWork) {
        this.mCallBackWork = callBackWork
    }

    /**
     * 回调接口
     */
    interface CallBackWork {
        /**
         * 停止倒计时
         */
        fun stopWork()

        /**
         * 获取倒计时中的时间
         */
        fun getCurrentSecond(mCurrentSecond: Int)
    }

}